package qq

import (
	"encoding/json"
	"errors"
	"log/slog"

	"gitee.com/gxcc/go-utils/utils"
)

type UserInfo struct {
	Ret          int    `json:"ret"`
	Msg          string `json:"msg"`
	Nickname     string `json:"nickname"`
	Gender       string `json:"gender"`
	FigureurlQQ1 string `json:"figureurl_qq_1"`
	FigureurlQQ2 string `json:"figureurl_qq_2"`
}

// GetUserInfo 获取授权的用户信息
func GetUserInfo(appId string, accessToken string, openid string) (*UserInfo, error) {
	url := "https://graph.qq.com/user/get_user_info?access_token=" +
		accessToken + "&oauth_consumer_key=" + appId +
		"&openid=" + openid
	res, err := utils.HttpGet(url, nil)
	if err != nil {
		slog.Error(err.Error())
		return nil, err
	}

	var qqUser UserInfo
	if err = json.Unmarshal(res.Body, &qqUser); err != nil {
		slog.Error(err.Error())
		return nil, err
	}
	if qqUser.Ret != 0 {
		return nil, errors.New(qqUser.Msg)
	}
	return &qqUser, nil
}
